//
//  BMSAppInfoHelper.m
//  WDBMS
//
//  Created by YeJary on 2025/5/12.
//

#import "BMSAppInfoHelper.h"
#import "BMSDataPersistenceManager.h"
#import "BMSDeviceInfo.h"

@interface BMSAppInfoHelper()


@end

@implementation BMSAppInfoHelper

+ (NSString *)bmsAppNameForInfoPlistFile {
    NSDictionary *dict = [BMSDataPersistenceManager readWDGroMoreSDKConfigFile];
    if (![dict isKindOfClass:[NSDictionary class]]) {
        NSLog(@"[BMS] JSON 配置无效");
        return @"";
    }

    NSDictionary *configDict = dict[@"bms"];
    if (![configDict isKindOfClass:[NSDictionary class]]) {
        NSLog(@"[BMS] bms 字段不是字典");
        return @"";
    }

    NSString *appName = configDict[@"app_name"];
    if (![appName isKindOfClass:[NSString class]] || appName.length == 0) {
        NSLog(@"[BMS] app_name 字段为空或类型错误");
        return @"";
    }

    return appName;
}

+ (NSString *)bmsChannelForSDKConfigFile {
    NSDictionary *dict = [BMSDataPersistenceManager readWDGroMoreSDKConfigFile];
    if (![dict isKindOfClass:[NSDictionary class]]) {
        return @"";
    }

    NSDictionary *configDict = dict[@"bms"];
    if (![configDict isKindOfClass:[NSDictionary class]]) {
        return @"";
    }

    NSString *channel = configDict[@"channel"];
    if (![channel isKindOfClass:[NSString class]] || channel.length == 0) {
        return @""; // 可选：返回默认渠道名 @"appstore"
    }

    return channel;
}

+ (NSString *)bmsAppVersionForInfoPlistFile {
    id version = [[NSBundle mainBundle].infoDictionary objectForKey:@"BMSVersion"];
    if ([version isKindOfClass:[NSString class]] && ((NSString *)version).length > 0) {
        return version;
    }
    return @"";
}

/// OpenId
+ (NSString *)getOpenId {
    // 设置openID
    NSString *openId = [[BMSDeviceInfo shared]UUID];
    return openId;
}

+ (NSString *)generateNonce {
    static NSString *charset = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
    NSUInteger minLength = 16;
    NSUInteger maxLength = 64;
    NSUInteger length = arc4random_uniform((uint32_t)(maxLength - minLength + 1)) + minLength;

    NSMutableString *result = [NSMutableString stringWithCapacity:length];
    for (NSUInteger i = 0; i < length; i++) {
        uint32_t index = arc4random_uniform((uint32_t)charset.length);
        unichar c = [charset characterAtIndex:index];
        [result appendFormat:@"%C", c];
    }
    return result;
}

+ (NSInteger)currentTimestamp {
    return (NSInteger)[[NSDate date] timeIntervalSince1970];
}

@end
